// pages/history-bill/history-bill.js
var util = require('../../utils/util.js')
var app = getApp();
var startDate, endDate;
Page({
  data:{
    historyBillList: [],
    scrollHeight: "100%",
  },

  onLoad() {
    let today = (util.formatTime(new Date())).split(' ')[0];
    startDate = (util.formatTime(new Date(new Date().getTime() - 7 * 24 * 60 * 60 * 1000))).split(' ')[0], endDate = today;
    this.setData({
      today: today,
      endDate: today.split('-')[1] + '月' + today.split('-')[2] + '日', 
      startDate: startDate.split('-')[1] + '月' + startDate.split('-')[2] + '日'
    });
  },

  onShow(){
    console.log(new Date(startDate), new Date(startDate).getTime())
    this.refresh(new Date(startDate).getTime(), new Date(endDate).getTime())
  },

  startDate(e) {
    startDate = e.detail.value;
    let date = e.detail.value.split('-');
    this.setData({ startDate: date[1] + '月' + date[2] + '日' });
    this.refresh(new Date(e.detail.value).getTime(), new Date(endDate).getTime())

  },

  endDate(e) {
    endDate = e.detail.value;
    let date = e.detail.value.split('-');
    this.setData({ endDate: date[1] + '月' + date[2] + '日' });
    this.refresh(new Date(startDate).getTime(), new Date(e.detail.value).getTime())
  },

  refresh(start, end) {
    console.log(start, end)
    let bill = wx.getStorageSync('Bill'), tot_income = 0, tot_expend = 0;
    for (let i = 0; i < bill.length; ++i) {
      if (new Date(bill[i].date).getTime() > end || new Date(bill[i].date).getTime() < start) continue;
      console.log(parseInt(bill[i].spendMoney), parseInt(bill[i].spendMoney) > 0)
      if (parseInt(bill[i].spendMoney) > 0) tot_income += parseInt(bill[i].spendMoney)
      else tot_expend -= parseInt(bill[i].spendMoney)
    }

    this.setData({
      historyBillList: bill,
      tot_expend,
      tot_income,
    })
    console.log(bill)
  },

})